package com.liangli.thread.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类，启用线程池
 *
 * @Author: liangli
 * Date: 2021/10/9 17:55
 * Description:
 */

@Configuration
@EnableAsync
public class TaskExecutorConfig {

    @Bean(name = "taskExecutor")
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //最小线程数
        executor.setCorePoolSize(10);
        //最大线程数
        executor.setMaxPoolSize(20);
        //等待队列数
        executor.setQueueCapacity(200);
        //线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        //默认线程前缀名
        executor.setThreadNamePrefix("liang-sync--");
        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有任务结束后在关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);

        return executor;
    }

}
